package com.spsoft.vms.redis.config;

import cn.hutool.core.util.StrUtil;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import org.redisson.config.SentinelServersConfig;
import org.redisson.config.SingleServerConfig;
import org.redisson.spring.data.connection.RedissonConnectionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * redisson配置类
 *
 * @author : chenxudong
 * @date : 2024/3/13 17:28
 */
@Configuration
public class RedissonConfig {

    @Value(value = "${spring.redis.sentinel.master:}")
    private String sentinelMaster;

    @Value(value = "${spring.redis.sentinel.nodes:}")
    private String sentinelNodes;

    @Value(value = "${spring.redis.database:}")
    private int redisDatabase;

    @Value(value = "${spring.redis.password:}")
    private String redisPassword;

    @Value(value = "${spring.redis.host:}")
    private String redisHost;

    @Value(value = "${spring.redis.port:}")
    private String redisPort;

    @Bean(destroyMethod = "shutdown")
    public RedissonClient redissonClient() {
        Config config = new Config();
        // sentinel哨兵模式
        if (StrUtil.isNotBlank(sentinelMaster)) {
            SentinelServersConfig sentinelServersConfig = config.useSentinelServers();
            sentinelServersConfig.setMasterName(sentinelMaster);
            List<String> nodeList = new ArrayList<>();
            String[] nodes = sentinelNodes.split(",");
            for (String node : nodes) {
                nodeList.add("redis://" + node);
            }
            sentinelServersConfig.addSentinelAddress(nodeList.toArray(new String[0]));
            sentinelServersConfig.setDatabase(redisDatabase);
            if (StrUtil.isNotBlank(redisPassword)) {
                sentinelServersConfig.setPassword(redisPassword);
            }
        } else { // 单节点模式
            SingleServerConfig singleServerConfig = config.useSingleServer();
            singleServerConfig.setAddress("redis://" + redisHost + ":" + redisPort);
            singleServerConfig.setDatabase(redisDatabase);
            if (StrUtil.isNotBlank(redisPassword)) {
                singleServerConfig.setPassword(redisPassword);
            }
        }
        // 设置序列化器为JSON，防止出现乱码
        config.setCodec(new JsonJacksonCodec());
        return Redisson.create(config);
    }

    @Bean
    public RedissonConnectionFactory redissonConnectionFactory(RedissonClient redisson) {
        return new RedissonConnectionFactory(redisson);
    }
}
